package com.ddone.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpCookie;
import org.springframework.http.ResponseCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.UUID;

/**
 * @author ddone
 * @date 2024/4/7-15:19
 */
@Component
public class DemoTokenGatewayFilterFactor extends AbstractGatewayFilterFactory {


    @Override
    public GatewayFilter apply(Object config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                ServerHttpRequest request = exchange.getRequest();
                MultiValueMap<String, HttpCookie> cookies = request.getCookies();
                HttpCookie httpCookie = cookies.getFirst("token");
                if(httpCookie==null){
                    request.mutate().header("cookie","token="+ResponseCookie.from("token", UUID.randomUUID().toString())
                            .build());
                }
                // 放行
                return chain.filter(exchange);
            }
        };
    }

    @Override
    public String name() {
        return "DemoToken";
    }
}
